package com.mvp.lt.airlineview.record;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.os.IBinder;

import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.util.DisplayMetrics;
import android.view.WindowManager;


import com.mvp.lt.airlineview.App;
import com.mvp.lt.airlineview.utils.LogUtil;

import java.util.Objects;

import static android.content.Context.MEDIA_PROJECTION_SERVICE;

/**
 * 录屏工具类
 *
 * @author Liutao
 */

public class ScreenRecorderUtils {

    private MediaProjectionManager projectionManager;
    private static final int RECORD_REQUEST_CODE = 101;
    private static final int STORAGE_REQUEST_CODE = 102;
    private static final int AUDIO_REQUEST_CODE = 103;
    public static final String RESULT_CODE = "RESULT_CODE";
    public static final String RESULT_DATA = "RESULT_DATA";
    //application context is better
    public static ScreenRecorderUtils getInstance() {
        if (mRecorder == null) {
            mRecorder = new ScreenRecorderUtils();
        }
        return mRecorder;
    }

    private RecordService recordService;

    private static volatile ScreenRecorderUtils mRecorder;
    private Context mcontext;

    private ScreenRecorderUtils() {
        mcontext = App.getContext();
    }

    public boolean isRunning() {
        return recordService.isRunning();
    }

    public RecordService getRecordService() {
        return recordService;
    }

    @SuppressLint("NewApi")
    public void initRecordService() {
        ServiceConnection connection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName className, IBinder service) {
                LogUtil.e("录屏服务", "===============onServiceConnected===========");
                RecordService.RecordBinder binder = (RecordService.RecordBinder) service;
                WindowManager wm = (WindowManager) App.getContext().getSystemService(Context.WINDOW_SERVICE);
                DisplayMetrics outMetrics = new DisplayMetrics();
                Objects.requireNonNull(wm).getDefaultDisplay().getMetrics(outMetrics);
                recordService = binder.getRecordService();
                recordService.setConfig(outMetrics.widthPixels, outMetrics.heightPixels, outMetrics.densityDpi);
                projectionManager = (MediaProjectionManager) mcontext.getSystemService(MEDIA_PROJECTION_SERVICE);
                recordService.setProjectionManager(projectionManager);
            }

            @Override
            public void onServiceDisconnected(ComponentName arg0) {

            }
        };
        Intent intent = new Intent(mcontext, RecordService.class);
        mcontext.bindService(intent, connection, Context.BIND_AUTO_CREATE);
    }


    //stop record
    public void stopRecord(OnRecordStatusChangeListener listener) {
        if (recordService != null && recordService.isRunning()) {
            if (recordService.stopRecord()) {
                //stop record success
                listener.onChangeSuccess();
            } else {
                //stop record failed
                listener.onChangeFailed();
            }
        }
    }

    public void stopRecord() {
        if (recordService != null && recordService.isRunning()) {
            recordService.stopRecord();
        }
    }


    /**
     * 停止录屏服务
     *
     * @param context
     */
    public void stopRecprdSerVice(Context context) {
        context.stopService(new Intent(context, RecordService.class));
    }


    @SuppressLint("NewApi")
    public void startRecord(Activity activity) {
        projectionManager = (MediaProjectionManager) mcontext.getSystemService(MEDIA_PROJECTION_SERVICE);
        if (recordService.isRunning()) {
            recordService.stopRecord();
        } else {
            Intent captureIntent = projectionManager.createScreenCaptureIntent();
            activity.startActivityForResult(captureIntent, RECORD_REQUEST_CODE);
        }
        if (ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(activity,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, STORAGE_REQUEST_CODE);
        }

        if (ContextCompat.checkSelfPermission(activity, Manifest.permission.RECORD_AUDIO)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(activity,
                    new String[]{Manifest.permission.RECORD_AUDIO}, AUDIO_REQUEST_CODE);
        }
    }

    /**
     * 开始录制
     *
     * @param activity
     * @param width
     * @param height
     * @param dirpath
     * @param fileName
     * @param audio
     */
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public void startCustomRecord(Activity activity, final int width, final int height, String dirpath, String fileName, boolean audio) {
        LogUtil.e("录屏服务", dirpath);
        if (recordService == null) {
            LogUtil.e("录屏服务", "===============null===========");
            return;
        }
        LogUtil.e("录屏服务", dirpath);
        recordService.setRecorderConfig(width, height, dirpath, fileName, audio);
        if (recordService.isRunning()) {
            recordService.stopRecord();
        } else {
            LogUtil.e("录屏服务", dirpath);
            projectionManager = (MediaProjectionManager) activity.getSystemService(MEDIA_PROJECTION_SERVICE);
            if (projectionManager != null) {
                Intent captureIntent = projectionManager.createScreenCaptureIntent();
                activity.startActivityForResult(captureIntent, RECORD_REQUEST_CODE);
            }
        }
        if (ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(activity,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, STORAGE_REQUEST_CODE);
        }

        if (ContextCompat.checkSelfPermission(activity, Manifest.permission.RECORD_AUDIO)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(activity,
                    new String[]{Manifest.permission.RECORD_AUDIO}, AUDIO_REQUEST_CODE);
        }
    }

    public interface OnRecordStatusChangeListener {
        //operate success
        void onChangeSuccess();

        //operate error
        void onChangeFailed();
    }

    public void onActivityResult(Context context, int requestCode, int resultCode, Intent data) {
        if (requestCode == RECORD_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            Intent service = new Intent(context, RecordService.class);
            service.putExtra(RESULT_CODE, resultCode);
            service.putExtra(RESULT_DATA, data);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.startForegroundService(service);
            } else {
                context.startService(service);
            }
        }
    }

    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == STORAGE_REQUEST_CODE || requestCode == AUDIO_REQUEST_CODE) {
            if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                //activity.finish();
            }
        }
    }



    public String getRecordFilePath() {
        if (recordService != null) {
            return recordService.getRecordFilePath();
        } else {
            return "";
        }

    }
}
